<template>
  <div id="app" class="electric-power" tabindex="0">
    <!-- 头部导航 -->
    <van-nav-bar left-arrow title="电耗记录" @click-left="comeBack" left-text="返回">
      <template #title>
        <span @click="preDayFn">前一天</span>
        <span @click="calendar.show = true" style="margin: 0 10px;color:#bb5a09;">{{ queryParam.beginAt }}</span>
        <span @click="nextDayFn">后一天</span>
      </template>
      <template #right>
        <van-icon size="1.5rem" name="plus" @click="showMeterPopFn"></van-icon>
      </template>
    </van-nav-bar>

    <!-- 筛选 -->
    <van-search v-model="queryParam.keyLike" placeholder="请输入搜索关键词" @search="() => loadElectricityConsumptionDataFn(1)"></van-search>

    <!-- 滚动 -->
    <better-scroll class="body-scroll" :data="electricityConsumptionData" :total-page="totalPage" :pulldown="true" :pullup="true" @pullup="loadNextPageFn" @pulldown="() => loadElectricityConsumptionDataFn(1)">
      <van-swipe-cell v-show="electricityConsumptionData.length > 0" v-for="(row, rIndex) in electricityConsumptionData" :key="row.id" style="padding-bottom: 0.5rem">
        <template>
          <div class="data-card">
            <div style="border-bottom: 1px solid #8191c5;" >
              <span style="color: #8191c5;font-size: 1.3rem; font-weight: bolder;">编号:{{ row.meterNo }}</span>
              <span style="color: #bb5a09;font-size: 1.1rem; ">{{ energyMeterTypeEnumFn(row.type) }}</span>
            </div>
            <div style="align-items: end">
              <span style="color: #38792e;font-size: 1.3rem; font-weight: bolder;">度数:{{ row.num }}</span>
              <span style="color: #38792e;font-size: 1.1rem; ">{{ row.optAt }}</span>
            </div>
          </div>
        </template>
<!--        <template #right>
          <div style="display: flex; flex-flow: column; padding-right: 2vw;">
            <van-button square size="small" type="warning" @click="showChangePicPopupFn(row)">上图</van-button>
            <van-button square style="margin-top: 1vh;" size="small" type="info" @click="showApplyForPopupFn(row)">采购申请</van-button>
            <van-button square style="margin-top: 1vh;" size="small" type="primary" @click="printLabel(row)">打印二维码</van-button>
          </div>
        </template>-->
      </van-swipe-cell>
      <van-empty  v-show="electricityConsumptionData.length == 0" image="https://img01.yzcdn.cn/vant/custom-empty-image.png" description="暂无数据" ></van-empty>
    </better-scroll>

    <!-- 日期筛选 -->
    <van-calendar v-model="calendar.show" :min-date="calendar.minDate" :max-date="calendar.maxDate" :round="false" @confirm="selectDayFn"></van-calendar>

    <!-- 电耗抄表 -->
    <van-popup class="meter-record" style="" v-model="change.show" get-container="#app">
      <div style="display: flex;justify-content: center;align-items:center; flex-flow: column">
        <div style="font-size: 1.2rem;color:#3b4ca4;">
          <span>位置:{{ energyMeterTypeEnumFn(change.type) }}</span>
        </div>
        <div style="font-size: 1.3rem;color:#3ba440;margin-top:1vh;">
          <span>编号:{{ change.meterNo }}</span>
        </div>
        <div style="margin-top:1vh;border-top: 1px solid #3b4ca4;border-bottom: 1px solid #3b4ca4;">
          <van-picker ref="consumptionNumPickerRef" :show-toolbar="false" :columns="numColumns" :visible-item-count="3" @change="changeNumFn">
            <template #columns-top>
              <div style="display: flex;justify-content: space-between;padding-left: 4vw;padding-right: 4vw;font-size: 1.1rem;border-bottom: 1px solid #3b4ca4;">
                <div>万</div>
                <div>千</div>
                <div>百</div>
                <div>十</div>
                <div>个</div>
                <div>点</div>
              </div>
            </template>
          </van-picker>
        </div>
      </div>
      <div style="display: flex;justify-content: center;margin-top: 2vh;">
        <van-button size="small" type="danger" @click="change.show = false">取消</van-button>
        <van-button size="small" style="margin-left: 10vw;" block type="info" @click="confirmChangeFn">确认</van-button>
      </div>
    </van-popup>

    <van-popup class="meter-list" v-model="meterPop.show" position="bottom">
<!--      <div style="width: 70vw;padding: 1vh 2vw; ">
        <div>
          <van-popover v-model="meterPop.showType" trigger="click" :actions="meterPop.types" @select="onSelect">
            <template #reference>
              <van-button type="primary">{{  }}</van-button>
            </template>
          </van-popover>
        </div>
        <div style="display: flex;">
          <van-button style="flex: 0 0 10vw;margin-right:2vw; margin-bottom: 1vh;font-size: 1.5rem" :color="meter.color" v-for="meter in meterPop.data" @click="">{{ meter.no }}</van-button>
        </div>
      </div>-->
      <van-picker ref="meterPickerRef" :show-toolbar="true" :columns="meterPop.data" @cancel="meterPop.show=false">
        <template #default>
          <div style="display: flex;justify-content: space-between;align-items: center;width: 100vw;padding-left: 2vw;padding-right: 2vw;">
            <div>
              <van-button type="danger" size="small" @click="meterPop.show = false">取消</van-button>
            </div>
            <div>
              <span style="font-size: 1.2rem;color: #2774b3">选择电表</span>
            </div>
            <div style="display: flex;align-items: center">
              <div>
                <van-button type="primary" size="small" @click.stop="selectMeterFn">确认选择</van-button>
              </div>
              <div>
                <van-icon style="margin-left: 3vw;" size="1.7rem" name="scan" @click.stop="openScanWinFn"></van-icon>
              </div>
            </div>
          </div>
        </template>
      </van-picker>
    </van-popup>
  </div>
</template>

<script>
import {comeBack, openWin, randomStr} from "@/utils";
import {
  ENERGY_METER_TYPE,
  energyMeterTypeEnumFn,
  SPARE_PART_RECYCLING_ENUM,
  SPARE_PART_ROOM_ENUM,
  SPARE_PART_TYPE_ENUM,
  sparePartStatusEnumFn,
  SPLIT_BLANK,
  SPLIT_COMMA, SPLIT_DOT,
  SPLIT_YKH,
  SPLIT_ZKH
} from "@/api/enum";
import {
  electricityConsumptionChange,
  electricityConsumptionList,
  electricMeterDetail, loadElectricMeterData
} from "@/views/energy-consumption/energy-consumption";
import dayjs from "dayjs";
import {randomColor} from "@/api/common";

export default {
  name: "electricPower",
  data() {
    return {
      SPLIT_ZKH, SPLIT_YKH, SPLIT_BLANK,

      /* 查询相关 */
      calendar: {
        show: false,
        minDate: new Date(dayjs().subtract(1, "year")),
        maxDate: new Date(),
      },
      queryParam: {
        keyLike: SPLIT_BLANK,
        pageNum: 1,
        pageSize: 10,
        beginAt: dayjs().format("YYYY-MM-DD"),
        endAt: dayjs().add(1, "day").format("YYYY-MM-DD"),
      },
      queryTimer: null,

      /* 所有电表 */
      meterPop: {
        show: false,
        // originalData: [],
        data: [],
        type: 1,
        // showType: false,
        // types: [],
      },


      /* 列表相关 */
      electricityConsumptionData: [],
      totalPage: 0,

      /* 新增更改 */
      change: {
        id: 0,
        show: false,
        type: 1,
        meterId: 0,
        meterNo: SPLIT_BLANK,
        num: 0
      },

      /* pick数据 */
      numColumns: [{
        values: ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"],
        defaultIndex: 0
      }, {
        values: ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"],
        defaultIndex: 0
      }, {
        values: ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"],
        defaultIndex: 0
      }, {
        values: ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"],
        defaultIndex: 0
      }, {
        values: ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"],
        defaultIndex: 0
      }, {
        values: ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"],
        defaultIndex: 0
      }],

    }
  },
  mounted() {
    const that = this;
    if (process.env.NODE_ENV === "production") {
      that.$nextTick(() => {
        that.initFn(that);
      });
    } else {
      window.apiready = function () {
        that.initFn(that);
      };
    }
  },
  methods: {
    comeBack, energyMeterTypeEnumFn,

    /* 初始化 */
    initFn() {
      const that = this;

      //加载电表数据
      loadElectricMeterData({}, data => {
        if(!data.code && data.code != 0) {
          Object.keys(ENERGY_METER_TYPE).forEach(key => {
            let type = {
              type: key,
              text: ENERGY_METER_TYPE[key],
              children: []
            };
            data.filter(meter => meter.type == key).forEach(meter => {
              type.children.push({
                text: meter.no,
                id: meter.id,
              });
            });
            if(type.children.length > 0) {
              that.meterPop.data.push(type);
            }
          });

        } else {
          that.$toast.fail(data.msg);
        }
      });

      //加载数据
      that.loadElectricityConsumptionDataFn(1);
    },

    /* 前一天 */
    preDayFn() {
      const that = this;
      that.queryParam.endAt = that.queryParam.beginAt;
      that.queryParam.beginAt = dayjs(that.queryParam.beginAt).subtract(1, "day").format("YYYY-MM-DD");
      that.loadElectricityConsumptionDataFn(1);
    },
    /* 后一天 */
    nextDayFn() {
      const that = this;
      if (that.queryParam.beginAt === dayjs().format("YYYY-MM-DD")) {
        that.$toast.fail("明天还没到");
        return false;
      }
      that.queryParam.beginAt = that.queryParam.endAt;
      that.queryParam.endAt = dayjs(that.queryParam.endAt).add(1, "day").format("YYYY-MM-DD");
      that.loadElectricityConsumptionDataFn(1);
    },
    /* 选择一趟 */
    selectDayFn(val) {
      const that = this;
      that.queryParam.beginAt = dayjs(val).format("YYYY-MM-DD");
      that.queryParam.endAt = dayjs(val).add(1, "day").format("YYYY-MM-DD");
      that.calendar.show = false;
      that.loadElectricityConsumptionDataFn(1);
    },

    /* 打开扫码窗 */
    openScanWinFn() {
      const that = this;
      const zyHmsScan = api.require('zyHmsScan');
      zyHmsScan.openDefaultView({}, ret => {
        if(ret.status) {
          if(ret.result.indexOf("38,") == 0) {    //备件码
            let ids = ret.result.split(SPLIT_COMMA);
            if(ids.length != 2) {
              that.$toast.fail("二维码异常");
              return;
            }

            that.change.show = true;    //这里必须先显示弹窗 才能获取到里面的组件
            that.$nextTick(() => {
              that.electricMeterDetailFn(ids[1]);
            });
          } else {
            that.$toast.fail("请扫电表码");
          }
        }
      });
    },

    /* 加载电号数据 */
    loadElectricityConsumptionDataFn(pageNum) {
      const that = this;
      if(pageNum == 1) {
        that.queryParam.pageNum = 1;
        that.electricityConsumptionData.splice(0, that.electricityConsumptionData.length);
      }
      electricityConsumptionList(that.queryParam, data => {
        if(!data.code && data.code != 0) {
          that.totalPage = data.totalPage;
          data.list.forEach(row => {
            that.electricityConsumptionData.push(row);
          });
        }
      });
    },

    /* 加载下一页 */
    loadNextPageFn() {
      let that = this;
      that.queryParam.pageNum++;
      that.loadElectricityConsumptionDataFn();
    },

    /* 电表详情 */
    electricMeterDetailFn(meterId) {
      const that = this;
      electricMeterDetail({
        meterId: meterId
      }, data => {
        if(!data.code && data.code != 0) {
          that.change.id = 0;
          that.change.type = data.type;
          that.change.meterId = data.id;
          that.change.meterNo = data.no;
          that.change.num = 0;
          if(data.lastConsumption) {
            let numTmp = String(data.lastConsumption.num);
            if(numTmp.indexOf(SPLIT_DOT) != -1) {   //小数去点 1位小数
              numTmp = numTmp.replace(SPLIT_DOT, SPLIT_BLANK)
            } else {
              numTmp = numTmp + "0";    //正数补0 1位小数
            }
            that.$refs.consumptionNumPickerRef.setValues(Array.from(numTmp.padStart(6, '0')));    //6位填充
          }
        } else {
          that.$toast.fail(data.msg);
        }
      });
    },

    /* 更改数字 */
    changeNumFn() {
      const that = this;
      that.change.num = (Number(that.$refs.consumptionNumPickerRef.getValues().join(SPLIT_BLANK)) / 10).toFixed(1);   //保留1位
    },

    /* 确认更改(新增) */
    confirmChangeFn() {
      const that = this;
      that.$toast.loading({
        message: "操作中...",
        forbidClick: true,
        duration: 60000,
        loadingType: "spinner"
      });
      electricityConsumptionChange(that.change, data => {
        if(!data.code && data.code != 0) {
          that.change.show = false;
          that.$toast({
            type: "success",
            message: "操作成功",
            overlay: true,
            forbidClick: true,
            onClose: () => {
              that.loadElectricityConsumptionDataFn(1);
            }
          });
        } else {
          that.$toast.fail(data.msg);
        }
      });
    },

    /* 显示仪表弹窗 */
    showMeterPopFn() {
      const that = this;
      that.meterPop.show = true;
    },

    /* 选择一个电表 */
    selectMeterFn() {
      const that = this;
      let values = that.$refs.meterPickerRef.getValues();
      that.meterPop.show = false;
      that.change.show = true;
      that.$nextTick(() => {
        that.electricMeterDetailFn(values[1].id);
      });
    },
  }
}
</script>

<style lang="scss" scoped>
.electric-power {
  height: 100%;
  ::v-deep .van-search {
    z-index: 1;
  }

  .body-scroll {
    height: 79vh;
    .data-card {
      width: 96vw;
      padding: 0 0.8rem;
      margin-left: 2vw;
      background-color: white;
      margin-top: 0.5rem;
      box-shadow: 0.3rem 0.5rem 0.3rem #888888;
      display: flex;
      flex-flow: column;
      div {
        display: flex;
        justify-content: space-between;
        padding: 0.3rem 0rem;
      }
    }
  }

  .meter-record {
    width: 70vw;
    padding: 1vh 2vw;
    ::v-deep .van-picker {
      width: 70vw;
      .van-picker__columns {
        .van-picker-column {
          .van-picker-column__item {
            font-size: 1.4rem;
          }
          .van-picker-column__item--selected {
            font-size: 2rem;
            font-weight: bolder;
            color: #19b601;
          }
          &:nth-child(6) {
            .van-picker-column__item {
              //color: #b64001 !important;
            }
            .van-picker-column__item--selected {
              font-size: 2.2rem;
              font-weight: bolder;
              color: #b64001;
            }
          }
        }
      }
    }
  }

  .meter-list {
    ::v-deep .van-picker {
      .van-picker__columns {
        .van-picker-column {
          .van-picker-column__item {
            font-size: 1.2rem;
          }
          .van-picker-column__item--selected {
            font-size: 1.4rem;
            font-weight: bolder;
            color: #0177b6;
          }
          &:nth-child(6) {
            .van-picker-column__item {
              //color: #b64001 !important;
            }
            .van-picker-column__item--selected {
              font-size: 1.5rem;
              font-weight: bolder;
              color: #b69e01;
            }
          }
        }
      }
    }
  }


}
</style>